package com.chenchao.net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/26 14:02
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.net.Test12C.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * TCP多线程客户端
 */
public class Test12C {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket=new ServerSocket(10000);
        /*新建serverSocket*/

        while (true){
            Socket accept = serverSocket.accept();
            Thread thread = new Thread(new TestServer(accept));
            thread.start();
        }

    }
}
class TestServer implements Runnable{

    Socket accept;
    /*获取接收的socket*/


    public TestServer(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        int count=0;
        File file = new File("myjava01/src/fo/img", "gg01.jpg");
        while (file.exists()){
            file=new File("myjava01/src/fo/img","gg"+count+++".jpg");
        }
        /*文件存在则创建新文件*/

        try (
                /*接收socket对象*/
                BufferedInputStream bis = new BufferedInputStream(accept.getInputStream());
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                OutputStream os = accept.getOutputStream())
        {
            byte[] bytes = new byte[1024];
            int len;
            /*网络流读入*/
            while ((len = bis.read(bytes)) != -1) {
                /*写入本地流*/
                bos.write(bytes, 0, len);
            }

            os.write("尊敬的客户，\n文件上传成功！".getBytes());
            /*网络流写出*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}